<?php
/**
 * @Notes:【】
 * @User: zwc
 * @Date: 2022-05-09 23:36
 */

namespace App\Service\WebSocket\Message;

use App\Constants\Talk\MessageEvent;
use App\Dao\Chat\ChatMessageDao;
use App\Dao\Chat\ChatRecordsDao;
use App\Dao\Chat\ChatSessionDao;
use App\Event\Talk\ChatEvent;
use App\Event\Talk\StartChatEvent;
use App\Service\WebSocket\SocketClientService;
use App\Util\JwtAuth;
use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Server\ServerFactory;

class ChatService
{
    /**
     * @Inject()
     * @var JwtAuth
     */
    protected $jwtAuth;
    /**
     * @Inject()
     * @var ChatMessageDao
     */
    protected $chatMessageDao;

    /**
     * @Inject()
     * @var SocketClientService
     */
    protected $socketClientService;
    /**
     * @Inject()
     * @var ChatRecordsDao
     */
    protected $chatRecordsDao;

    /**
     * @Inject()
     * @var ChatSessionDao
     */
    protected $chatSessionDao;

    public function startChat(StartChatEvent $startChatEvent){
        //记录session
        $this->chatSessionDao->add($startChatEvent->sender_id, $startChatEvent->friend_id, 0);
    }
    public function handle(ChatEvent $chatEvent)
    {
        //解析token
//        [$user_id,] = $this->jwtAuth->parseToken($chatEvent->token);
        Db::beginTransaction();
        try {
            dump($chatEvent);
            //创建文本消息
            $chatMessage = $this->chatMessageDao->text(
                $chatEvent->content,
                $chatEvent->types,
                $chatEvent->sender_id
            );

            $message = $chatEvent->toArray() + $chatMessage->toArray();
            //添加记录
            $this->chatRecordsDao->create([
                'receiver_id' => $chatEvent->receiver_id,
                'user_id' => $chatEvent->sender_id,
                'chat_message_id' => $chatMessage->id,
            ]);

            //记录session
            $this->chatSessionDao->add($chatEvent->sender_id, $chatEvent->receiver_id, $chatMessage->id);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            _Error($e->getMessage());
        }

        //获取发送人fd
        $senderFD = $this->socketClientService->getFds($chatEvent->sender_id, 1);
        $receiverFD = $this->socketClientService->getFds($chatEvent->receiver_id, 1);

        $this->send(array_merge($senderFD,$receiverFD), MessageEvent::PRIVATE_MESSAGE_RECEIVED,
            $message);
        return true;
    }


    private function toJson(string $event, array $data): string
    {
        return json_encode(["event" => $event, "content" => $data]);
    }


    public function send($fd, $event, $message)
    {
        $this->socketClientService->send($fd, $this->toJson($event, $message));
    }


}